package service;

import java.util.List;

import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import model.Item;
import persistence.PersistenceManager;

/**
 * Session Bean implementation class Catalog
 */
@Stateless
@WebService
public class Catalog  {

	//@PersistenceContext(unitName = "catserv")
	//private EntityManager entityManager;

    public Catalog() {
    	super();
    }

    @WebMethod
    public List<Item> getItems(int firstItem, int batchSize) {
        if (firstItem < 0) {
            firstItem = 0;
        }
      	EntityManager em = PersistenceManager.getEntityManager();
        Query q = em.createQuery("select object(o) from Item as o");
        q.setMaxResults(batchSize);
        q.setFirstResult(firstItem);
        return q.getResultList();
    }
    
    @WebMethod
    public Item getItem(String id) {
    	EntityManager em = PersistenceManager.getEntityManager(); 
        Item o = (Item) em.find(Item.class, id);
        return o;
    }
    
  
    @WebMethod
	public Item create() {
		Item newb = new Item();
		newb.setName("noname");
		newb.setDescription("..");
		newb.setProductid(0);
		newb.setPrice(0.0);
		EntityManager em = PersistenceManager.getEntityManager();
		em.getTransaction().begin();  
		em.persist(newb);
		em.getTransaction().commit(); 
		return newb;
	}    
    
    @WebMethod
	public Item save(Item item) {
		EntityManager em = PersistenceManager.getEntityManager();
		em.getTransaction().begin();  
    	em.merge(item);
    	em.getTransaction().commit(); 
		return item;
	}    
    
    @WebMethod
    public int getItemCount() {
    	EntityManager em = PersistenceManager.getEntityManager();  
        int count = ((Long) em.createQuery("select count(o) from Item as o").getSingleResult()).intValue();
        return count;
    }

}
